package com.example.tkserver.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.tkserver.dao.UserDao;
import com.example.tkserver.entity.User;
import com.example.tkserver.service.interfaces.RabbitMQService;
import com.example.tkserver.service.interfaces.UserService;
import com.example.tkserver.utils.HttpClientUtils;
import com.example.tkserver.entity.MyException;
import com.example.tkserver.utils.wxutil.WXBizDataUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
@Log4j2
public class UserServiceImpl implements UserService {
    @Value("${weiXinAppid}")
    private String appid;
    @Value("${weiXinSecret}")
    private String secret;
    @Autowired
    UserDao userDao;

    @Autowired
    RabbitMQService rabbitMQService;

    @Override
    public User login(String code,String rawData,String signature,String iv,String encryptedData){
        // 解密用户数据
        JSONObject userInfo = getUserInfo(code,rawData,signature,iv,encryptedData);
        // 如果解密成功
        if (userInfo != null){
            // 获取用户数据
            User user = new User();
            user.setOpenId(userInfo.getString("openId"));
            user.setNickName(userInfo.getString("nickName"));
            user.setAvatarUrl(userInfo.getString("avatarUrl"));
            user.setGender(userInfo.getIntValue("gender"));
            return loginOrRegister(user);
        }
        throw new MyException("登录失败！请联系管理员进行反馈！");
    }

    @Override
    public User updateUser(User user) {
        if (userDao.updateUser(user) == -1){
            throw new MyException("修改信息失败，请联系管理员进行反馈！");
        }
        return user;
    }

    //登录或自动注册
    public User loginOrRegister(User user){
        log.info("登录"+user);
        // 数据库查找用户
        User loginUser = userDao.findByOpenId(user.getOpenId());
        if (loginUser != null){ //如果用户存在
            log.info("登录完成"+loginUser);
            loginUser.setLoginType(1);
            return loginUser;
        }else{                  //如果用户不存在
            log.info("用户不存在,进行注册"+user);
            // 生成注册时间和最后登录时间
            user.setRegisterTime(System.currentTimeMillis()/1000);
            user.setLastTime(System.currentTimeMillis()/1000);
            user.setNickName("新用户"+user.getOpenId().substring(0,10));
            if (userDao.saveUser(user) == -1){
                throw new MyException("登录失败！请联系管理员进行反馈！");
            }
            // 给新注册的用户 发送欢迎消息
            rabbitMQService.sendHelloMsg(user.getUid());
            user.setLoginType(0);
            log.info("注册完成"+user);
            return user;
        }
    }

    //解密用户数据
    public JSONObject getUserInfo(String code, String rawData,String signature,String iv,String encryptedData) {
        try {
            // 向微信服务器发生请求 获取用户的sessionKey 和 openID
            JSONObject object = HttpClientUtils.get("https://api.weixin.qq.com/sns/jscode2session?appid="+appid
                    +"&secret="+secret+"&js_code=" + code+"&grant_type=authorization_code");
            String sessionKey = object.getString("session_key");
            String openId = object.getString("openid");
            log.info("获取sessionKey:"+sessionKey+" , OpenId:"+openId);
            // 如果校验通过的话
            if (WXBizDataUtil.getsignature2(rawData,sessionKey).equals(signature)){
                JSONObject userInfo = WXBizDataUtil.getUserInfo(iv,encryptedData,sessionKey);
                userInfo.put("openId",openId);
                log.info("获取用户数据:"+userInfo.toJSONString());
                return userInfo;
            }
        }catch (Exception e){
            log.error("发生错误",e.getMessage(),e);
        }
        return null;
    }
}
